package com.zhike.service.scheduled;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.zhike.common.dto.MsgBody4Group;
import com.zhike.common.dto.MsgBodyGroupS2C;
import com.zhike.common.dto.MsgType;
import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.model.ChatSession;
import com.zhike.common.model.GroupMembers;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.service.group.IGroupMemberService;
import com.zhike.service.im.manager.ChatManager4Group;
import com.zhike.service.im.manager.GroupMessageManager;
import com.zhike.service.im.manager.StorageMessage;
import com.zhike.service.messages.IChatSessionService;
import com.zhike.utils.cache.UsersInfoCacheProvider;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class GroupProhibitScheduledService {

    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private IGroupMemberService groupMemberService;

    @Autowired
    private UsersInfoCacheProvider usersInfoCacheProvider;

    @Autowired
    private IChatSessionService chatSessionService;

    @Autowired
    private ChatManager4Group chatManager4Group;

    private String groupId;

    private String userId;

    public GroupProhibitScheduledService() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    }

    /**
     * 启用当前群成员禁言定时任务
     * 
     * @param groupId
     * @param userId
     */
    @SuppressWarnings("rawtypes")
    public ScheduledFuture startTask(String groupId, String userId) {
        ScheduledFuture future = scheduledExecutorService.scheduleAtFixedRate(() -> {
            log.info("定时任务 t: {}", System.currentTimeMillis());
            GroupMembers gm = groupMemberService.selectGroupMemberInfo(groupId, userId);
            if (null != gm && gm.getProhibitMsg().equals(YesNoEnum.YES.getValue()) && gm.getMsgTimeEnd() > 0) {
                if (gm.getMsgTimeEnd() >= System.currentTimeMillis()) { // 禁言时间结束
                    try {
                        UserInfo4Cache uc = usersInfoCacheProvider.get(userId);
                        // 发消息
                        chatManager4Group.sendMsgOrSave4Group(new GroupMessageManager(groupId, "") {

                            @Override
                            public String buildGroupBody(MsgBody4Group root) {
                                MsgBodyGroupS2C cmdBody = new MsgBodyGroupS2C();
                                cmdBody.setUserId(userId);
                                cmdBody.setNickname(uc.getNickName());
                                cmdBody.setCGroup(41);

                                root.setF("0");
                                root.setT(groupId);
                                root.setTy(MsgType.TYPE_PROHIBIT);
                                root.setM(new Gson().toJson(cmdBody));
                                return new Gson().toJson(root);
                            }

                        }, new StorageMessage() {

                            @Override
                            public String getSessionId() {
                                ChatSession cs = chatSessionService.selectGroupSession(userId, groupId);
                                if (null != cs) {
                                    return cs.getSessionId();
                                }
                                return "";
                            }

                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }, 0, 5, TimeUnit.SECONDS);
        return future;
    }

    /**
     * 关闭ScheduledExecutorService，不再接受新任务，等待已提交任务执行完成
     */
    public void stopTask() {
        scheduledExecutorService.shutdown();
    }
}
